package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.turing.post.organization.util.VoucherStockDetail;
import com.turing.post.organization.util.VoucherStockDetailDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * @author wzd
 * @2013-03-12
 */
@Stateless(mappedName = "organization.impl.VoucherStockDetailDaoImpl")
@Remote
@Local
public class VoucherStockDetailDaoImpl implements VoucherStockDetailDao {

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	private static final String grpSumSql = ""
	// 采购入库
			+ "sum(case when t.tranType = '0' then t.count else 0 end), "
			// 调拨入库
			+ "sum(case when t.tranType = '1' then t.count else 0 end), "
			// 调拨出库
			+ "sum(case when t.tranType = '2' then t.count else 0 end), "
			// 盘盈入库
			+ "sum(case when t.tranType = '3' then t.count else 0 end), "
			// 业务出库 + 作废出库
			+ "sum(case when t.tranType = '4' or t.tranType = '5' then t.count else 0 end), "
			// 丢失损坏出库
			+ "sum(case when t.tranType = '9' then t.count else 0 end) ";

	/**
	 * 根据条件查询凭证出入库明细列表
	 * 
	 * @param BranchNo
	 *            机构号
	 * @param tranType
	 *            交易类型
	 * @param voucherId
	 *            凭证种类
	 * @param startDate
	 *            起始日期
	 * @param endDate
	 *            终止日期
	 * @param page
	 *            页码
	 * @return 凭证入库单明细列表
	 */
	@SuppressWarnings("unchecked")
	public List<VoucherStockDetail> getVoucherStockDetailList(
			PCPSWebInput webInput, String BranchNo, String tranType,
			BigInteger voucherId, String startDate, String endDate, Integer page) {
		if (webInput == null || PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| PCPSUtil.isEmpty(startDate) || PCPSUtil.isEmpty(endDate))
			return null;
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		String issuecompanyno = PCPSUtil.getIssueCompanyNo(webInput);
		String sql = "select * from VoucherStockDetail where IssueCompanyNo=?3 and TranTime>=to_date(?1,'yyyy-mm-dd hh24:mi:ss') and TranTime<=to_date(?2,'yyyy-mm-dd hh24:mi:ss')";
		if (webInput.isAll()==true)
			sql = sql + " and BranchNo='" + BranchNo + "'";
		else{
			sql+="  and BRANCHNO in (select subBranchNo from sysbranchsubord t where t.branchno=?4)";
		}
		if (!PCPSUtil.isEmpty(tranType)) {
			sql = sql + " and tranType = '" + tranType + "'";
		}
		if (voucherId != null) {
			sql = sql + " and VoucherId = " + voucherId + "";
		}
		sql = sql + " order by TranTime desc";
		Query query = _em.createNativeQuery(sql, VoucherStockDetail.class)
				.setFirstResult(startPosition).setMaxResults(maxResult);
		query.setParameter(1, startDate);
		query.setParameter(2, endDate);
		query.setParameter(3, issuecompanyno);
		query.setParameter(4, BranchNo);
		return query.getResultList();
	}

	/**
	 * 根据条件查询凭证出入库明细记录数
	 * 
	 * @param BranchNo
	 *            机构号
	 * @param tranType
	 *            交易类型
	 * @param voucherId
	 *            凭证种类
	 * @param startDate
	 *            起始日期
	 * @param endDate
	 *            终止日期
	 * @return 凭证库存表录数
	 */
	@Override
	public BigInteger getVoucherStockDetailListTotal(PCPSWebInput webInput,
			String BranchNo, String tranType, BigInteger voucherId,
			String startDate, String endDate) {
		if (webInput == null || PCPSUtil.isEmpty(webInput.getOperBranchNo())
				|| PCPSUtil.isEmpty(startDate) || PCPSUtil.isEmpty(endDate))
			return  new BigInteger("0");
		String issuecompanyno = PCPSUtil.getIssueCompanyNo(webInput);
		String sql = "select nvl(count(*),0) from VoucherStockDetail where   IssueCompanyNo=?3 and TranTime>=to_date(?1,'yyyy-mm-dd hh24:mi:ss') and TranTime<=to_date(?2,'yyyy-mm-dd hh24:mi:ss')";
		if (webInput.isAll()==true)
			sql = sql + " and BranchNo='" + BranchNo + "'";
		else{
			sql+="  and BRANCHNO in (select subBranchNo from sysbranchsubord t where t.branchno=?4)";
		}
		if (!PCPSUtil.isEmpty(tranType)) {
			sql = sql + " and tranType = '" + tranType + "'";
		}
		if (voucherId != null) {
			sql = sql + " and VoucherId = " + voucherId + "";
		}
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, startDate);
		query.setParameter(2, endDate);
		query.setParameter(3, issuecompanyno);
		query.setParameter(4, BranchNo);
		return new BigInteger(query.getSingleResult().toString());
	}

	/**
	 * 新增凭证出入库明细
	 * 
	 * @param VoucherStockDetail
	 *            凭证出入库明细
	 * @throws PCPSApplicationException
	 */
	@Override
	public void insertVoucherStockDetail(VoucherStockDetail voucherStockDetail)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, voucherStockDetail);
	}

	/**
	 * 删除凭证出入库明细表
	 * 
	 * @param VoucherStockDetail
	 *            凭证出入库明细表
	 * @throws PCPSApplicationException
	 */
	public void deleteVoucherStockDetail(VoucherStockDetail voucherStockDetail)
			throws PCPSApplicationException {
		VoucherStockDetail VoucherStockDetail1 = _em.find(
				VoucherStockDetail.class, voucherStockDetail);
		if (VoucherStockDetail1 != null)
			GeneralDao.remove(_em, VoucherStockDetail1);
	}

	/**
	 * 汇总某机构某日凭证日结数据
	 * 
	 * @param issueCompanyNo
	 * @param branchNo
	 *            (可选)
	 * @param tranDate
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Object[]> getVoucherStockDaySettlementByBranchNoAndTranDate(
			String issueCompanyNo, String branchNo, Date tranDate) {
		Query query = _em
				.createNativeQuery("select t.branchNo, t.voucherId, "
						+ grpSumSql
						+ " from VoucherStockDetail t "
						+ "where t.issueCompanyNo = ?1 AND (t.branchNo = ?2 or ?2 is NULL) and t.tranDate = ?3 "
						+ "group by t.branchNo, t.voucherId ");
		query.setParameter(1, issueCompanyNo);
		if (PCPSUtil.isEmpty(branchNo))
			query.setParameter(2, null);
		else
			query.setParameter(2, branchNo);
		query.setParameter(3, tranDate);
		List<Object[]> obj_list = query.getResultList();
		return obj_list;
	}
	/**
	 * 根据id，发卡商号检索迁移明细列表
	 */
	@SuppressWarnings("unchecked")
	public List<VoucherStockDetail> getVoucherStockDetailByid(String IoOrderId,String issuecompanyno){
		if (PCPSUtil.isEmpty(issuecompanyno)|| PCPSUtil.isEmpty(IoOrderId))
			return null;
		String sql = "select * from VoucherStockDetail where IssueCompanyNo=?1 and IOORDERID=?2";
		sql = sql + " order by TranTime asc";
		Query query = _em.createNativeQuery(sql, VoucherStockDetail.class);
		query.setParameter(1, issuecompanyno);
		query.setParameter(2, IoOrderId);
		return query.getResultList();
	}
	/**
	 * 根据id修改状态
	 */
	public void updateVoucherStockDetail(BigInteger ioOrderId)throws PCPSApplicationException{
		String sql = "update VoucherStockDetail set tranType='C'  where ioOrderId=?1";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, ioOrderId);
		query.executeUpdate();
	}
}
